<template>
  <div id="search-collection">
    <div v-if="searchCollections.count != 0">
      <div class="col-box">
        <CollectionItem
          class="col-item"
          v-for="item in searchCollections.data"
          :colData="item"
          :key="item.id"
        />
      </div>
    </div>
    <div class="pagination" v-if="searchCollections.count != 0">
      <el-pagination
        :page-size="pageSize"
        :pager-count="5"
        layout="prev, pager, next"
        :current-page="pageIndex"
        :total="searchCollections.count"
        background
        @prev-click="prevPage"
        @next-click="nextPage"
        @current-change="pageChange"
      >
      </el-pagination>
    </div>
    <div class="no-result" v-if="searchCollections.count == 0">
      <span>什么都没找到</span>
    </div>
  </div>
</template>

<script>
import CollectionItem from "@/components/CollectionItem";
import { mapState } from "vuex";
export default {
  name: "SearchCollection",
  components: {
    CollectionItem,
  },
  data() {
    return {
      keyword: "",
      pageSize: 20,
      pageIndex: 1,
    };
  },
  watch: {
    "$route.query": {
      immediate: true,
      handler(newValue) {
        this.keyword = newValue.keyword;
        this.$store.dispatch("searchCollections", {
          keyword: this.keyword,
          type: "array",
          pageSize: this.pageSize.toString(),
          pageIndex: this.pageIndex.toString(),
        });
      },
    },
  },
  mounted() {
    this.keyword = this.$route.query.keyword;
    this.$store.dispatch("searchCollections", {
      keyword: this.keyword,
      type: "array",
      pageSize: this.pageSize.toString(),
      pageIndex: this.pageIndex.toString(),
    });
  },
  computed: {
    ...mapState({
      searchCollections: (store) => store.search.searchCollections,
    }),
  },

  methods: {
    // 上一页
    prevPage() {
      this.pageIndex -= 1;
      this.$store.dispatch("searchCollections", {
        keyword: this.keyword,
        type: "array",
        pageSize: this.pageSize.toString(),
        pageIndex: this.pageIndex.toString(),
      });
    },
    // 下一页
    nextPage() {
      this.pageIndex += 1;
      this.$store.dispatch("searchCollections", {
        keyword: this.keyword,
        type: "array",
        pageSize: this.pageSize.toString(),
        pageIndex: this.pageIndex.toString(),
      });
    },

    // 页数改变
    pageChange(page) {
      this.pageIndex = page;
      this.$store.dispatch("searchCollections", {
        keyword: this.keyword,
        type: "array",
        pageSize: this.pageSize.toString(),
        pageIndex: this.pageIndex.toString(),
      });
    },
  },
};
</script>

<style lang='less'>
#search-collection {
  .no-result {
    height: 20vh;
    display: flex;
    justify-content: center;
    align-items: center;
    color: #999;
  }
}
</style>